<?php
/**
 * Dependency directory aggregator
 *
 * PHP version 5
 *
 * @category  W
 * @package   Services
 * @author    Olivier Hoareau <olivier@phppro.fr>
 * @copyright 2009 PHPPRO http://www.phppro.fr
 * @license   http://dev.phppro.fr/license PHPPRO
 * @version   SVN: $Id:$
 * @link      http://dev.phppro.fr/projects/wdependency
 */
require_once 'W/Dependency/Aggregator/Abstract.php';
/**
 * Dependency directory filter
 *
 * @category  W
 * @package   Services
 * @author    Olivier Hoareau <olivier@phppro.fr>
 * @copyright 2009 PHPPRO http://www.phppro.fr
 * @license   http://dev.phppro.fr/license PHPPRO
 * @version   SVN: $Id$
 * @link      http://dev.phppro.fr/projects/wdependency
 */
class W_Dependency_Aggregator_Directory extends W_Dependency_Aggregator_Abstract
{
    private $sep;
    private $depth;

    public function setSep($value)
    {
        $this->sep = $value;
    }
    public function setDepth($value)
    {
        $this->depth = $value;
    }
    public function reduce($data)
    {
        $d = array();
        $nodes = array_keys($data);
        foreach($nodes as $node) {
            $newNode = $this->formatNode($node,$this->sep,$this->depth);
            if (false === isset($d[$newNode])) {
                $d[$newNode] = array();
            }
            foreach($data[$node] as $item=>$weight) {
                $newItem = $this->formatNode($item,$this->sep,$this->depth);
                if (false === isset($d[$newNode][$newItem])) {
                    $d[$newNode][$newItem] = 0;
                }
                $d[$newNode][$newItem]+=$weight;
            }
        }
        return $d;
    }
    public function formatNode($node,$sep,$depth)
    {
        if (null === $sep) {
            $sep = '/';
        }
        if ('/' !== $sep) {
            $newNode = str_replace('%%%','/',str_replace('/',$sep,dirname(str_replace($sep,'/',str_replace('/','%%%',$node)))));
        }else{
            $newNode = dirname($node);
        }
        if (null !== $depth) {
            $newNode = join($sep,array_slice(explode($sep,$newNode),0,$depth+1));
        }
        return $newNode;
    }
}